package com.csun.cmny.provider.controller.admin;

import com.csun.cmny.core.annotation.ValidateAnnotation;
import com.csun.cmny.core.support.BaseController;
import com.csun.cmny.provider.device.csun.sleep.entity.CsunSleepData;
import com.csun.cmny.provider.model.domain.*;
import com.csun.cmny.provider.model.dto.csunsleep.BindCsunSleepDto;
import com.csun.cmny.provider.model.dto.csunsleep.CsunSleepPageQuery;
import com.csun.cmny.provider.model.dto.csunsleep.CsunSleepWifiDto;
import com.csun.cmny.provider.model.dto.device.DeviceBindDto;
import com.csun.cmny.provider.model.dto.device.DmcEditDeviceDto;
import com.csun.cmny.provider.model.enums.csunsleep.DmcCsunSleepBindTypeEnum;
import com.csun.cmny.provider.model.enums.device.DeviceStatusEnum;
import com.csun.cmny.provider.model.enums.device.DmcDeviceTypeEnum;
import com.csun.cmny.provider.model.vo.OldmanBedRoomBuildingVo;
import com.csun.cmny.provider.model.vo.RoomBuildingVo;
import com.csun.cmny.provider.model.vo.SleepAlertByHour;
import com.csun.cmny.provider.model.vo.csunsleep.DmcCsunSleepVo;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.*;
import com.csun.cmny.provider.utils.DeviceUtils;
import com.csun.cmny.util.PubUtils;
import com.csun.cmny.util.PublicUtil;
import com.csun.cmny.util.RedisKeyUtil;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-01-08 13:27
 * @Description: the class dmc device csun sleep controller.
 */
@RestController
@RequestMapping(value = "/csunSleep", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class DmcCsunSleepController extends BaseController {

    @Resource
    private DeviceUtils deviceUtils;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private CmnyMessageSource cmnyMessageSource;
    @Resource
    private DmcDeviceService dmcDeviceService;
    @Resource
    private DmcCsunSleepBindService dmcCsunSleepBindService;
    @Resource
    private DmcCsunSleepDataService dmcCsunSleepDataService;
    @Resource
    private DmcCsunSleepDataHiService dmcCsunSleepDataHiService;
    @Resource
    private DmcCsunSleepWifiService dmcCsunSleepWifiService;
    @Resource
    private OmcRpcService omcRpcService;
    @Resource
    private DmcDeviceOnlineRecordService dmcDeviceOnlineRecordService;
    @Resource
    private DmcDeviceAlertService dmcDeviceAlertService;

    /**
     * 查询组织日创床垫设备列表
     *
     * @param csunSleepPageQuery   the csun sleep page query
     *
     * @return  the wrapper
     */
    @ApiOperation(httpMethod = "POST", value = "查询组织日创床垫设备列表")
    @RequestMapping(value = "/queryGroupCsunSleepListWithPage", method = RequestMethod.POST)
    public Wrapper queryGroupCsunSleepListWithPage(@RequestBody CsunSleepPageQuery csunSleepPageQuery) {

        csunSleepPageQuery.setGroupId(getLoginAuthDto().getGroupId());
        csunSleepPageQuery.setDeviceType(DmcDeviceTypeEnum.CSUN_SLEEP.getIndex());

        PageInfo pageInfo = dmcCsunSleepBindService.queryGroupCsunSleepListWithPage(csunSleepPageQuery);
        for (Object o : pageInfo.getList()) {
            DmcCsunSleepVo dmcCsunSleepVo = (DmcCsunSleepVo) o;
            CsunSleepData csunSleepData = (CsunSleepData) redisTemplate.opsForValue()
                    .get(RedisKeyUtil.getCsunSleepKey(dmcCsunSleepVo.getDeviceNo()));

            /*
            * 2020-03-17 xuchongran
            * 改变床垫在线状态判别
            * */
//            if (PublicUtil.isEmpty(csunSleepData)) {
            dmcCsunSleepVo.setStatus(DeviceStatusEnum.OFFLINE.getKey());
//            }
//            else {
//                dmcCsunSleepVo.setStatus(csunSleepData.getStatus());
//            }
            if (!PubUtils.isNull(dmcCsunSleepVo.getBindType())) {
                if(redisTemplate.hasKey(RedisKeyUtil.getCsunSleepOnline(dmcCsunSleepVo.getDeviceNo()))){
                    dmcCsunSleepVo.setStatus(DeviceStatusEnum.ONLINE.getKey());
                }
                dmcCsunSleepVo.setBind(true);
                if (dmcCsunSleepVo.getBindType().equals(DmcCsunSleepBindTypeEnum.LIFE_ROOM.getKey())) {
                    RoomBuildingVo roomBuildingVo = (RoomBuildingVo) redisTemplate
                            .opsForValue().get(RedisKeyUtil.getOmcRoomId(dmcCsunSleepVo.getRoomId()));
                    if (PublicUtil.isNotEmpty(roomBuildingVo)) {
                        dmcCsunSleepVo.setBuildingName(roomBuildingVo.getBuildingName());
                        dmcCsunSleepVo.setFloorNo(roomBuildingVo.getFloorNo());
                        dmcCsunSleepVo.setRoomNo(roomBuildingVo.getRoomNo());
//                        dmcCsunSleepVo.setOldmanId(roomBuildingVo.getOldmanId());
//                        dmcCsunSleepVo.setOldmanName(roomBuildingVo.getOldmanName());
                        List<Integer> bedIdList = omcRpcService.listBedByRoomId(roomBuildingVo.getRoomId());
                        if(bedIdList != null && bedIdList.size() > 0){
                            OldmanBedRoomBuildingVo bov = (OldmanBedRoomBuildingVo) redisTemplate.opsForValue().get(RedisKeyUtil.getOmcBedId(bedIdList.get(0)));
                            dmcCsunSleepVo.setOldmanId(bov.getOldmanId());
                            dmcCsunSleepVo.setOldmanName(bov.getOldmanName());
                        }
                    }
                } else {
                    DeviceBindDto deviceBindDto = new DeviceBindDto();
                    BeanUtils.copyProperties(dmcCsunSleepVo, deviceBindDto);
                    OldmanBedRoomBuildingVo obrvo = deviceUtils.getOldmanBedRoomBuildingVo(deviceBindDto);
                    if (PublicUtil.isNotEmpty(obrvo)) {
                        if (dmcCsunSleepVo.getBindType().equals(DmcCsunSleepBindTypeEnum.OLDMAN.getKey())) {
                            dmcCsunSleepVo.setOldmanName(obrvo.getOldmanName());
                            if (PublicUtil.isNotEmpty(obrvo.getLocation())) {
                                /**
                                 * @date 2019-05-28
                                 * @author chisj
                                 * @desc 显示【房间-床位】 #2812
                                 */
                                if (PublicUtil.isNotEmpty(obrvo.getRoomNo()) && PublicUtil.isNotEmpty(obrvo.getBedNo())) {
                                    dmcCsunSleepVo.setLocation(obrvo.getRoomNo() + "-" + obrvo.getBedNo());
                                } else {
                                    dmcCsunSleepVo.setLocation("--");
                                }
                            }
                        }
                        /**
                         * @date 2019-05-06
                         * @author chisj
                         * @desc 解决老人换床后，依旧显示之前老人信息的bug #1832
                         */
                        // 绑定床位, 老人信息和位置根据床位获取
                        if (dmcCsunSleepVo.getBindType().equals(DmcCsunSleepBindTypeEnum.BED.getKey())) {
                            dmcCsunSleepVo.setOldmanName(obrvo.getOldmanName());
                            /**
                             * @date 2019-05-28
                             * @author chisj
                             * @desc 显示【房间-床位】 #2812
                             */
                            if (PublicUtil.isNotEmpty(obrvo.getRoomNo()) && PublicUtil.isNotEmpty(obrvo.getBedNo())) {
                                dmcCsunSleepVo.setLocation(obrvo.getRoomNo() + "-" + obrvo.getBedNo());
                            } else {
                                dmcCsunSleepVo.setLocation("--");
                            }
                            dmcCsunSleepVo.setOldmanId(obrvo.getOldmanId());
                        }
                    }
                }
            }
        }

      //  return WrapMapper.ok(pageInfo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),pageInfo);
    }

    /**
     * 添加日创床垫设备
     *
     * @param dmcEditDeviceDto  the dmc edit device dto
     * @param br                the binding result
     *
     * @return  the wrapper
     */
    @ValidateAnnotation
    @ApiOperation(httpMethod = "POST", value = "添加日创床垫设备")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Wrapper addCsunSleep(@Validated @RequestBody DmcEditDeviceDto dmcEditDeviceDto, BindingResult br) {

        DmcDevice dmcDevice = new DmcDevice();

        BeanUtils.copyProperties(dmcEditDeviceDto, dmcDevice);
        dmcDevice.setDeviceType(DmcDeviceTypeEnum.CSUN_SLEEP.getIndex());

        Integer result = dmcDeviceService.addDevice(dmcDevice, getLoginAuthDto());
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }

       // return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /**
     * 修改日创床垫设备
     *
     * @param dmcEditDeviceDto  the dmc edit device dto
     * @param br                the binding result
     *
     * @return  the wrapper
     */
    @ValidateAnnotation
    @ApiOperation(httpMethod = "POST", value = "修改日创床垫设备")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Wrapper editCsunSleep(@Validated @RequestBody DmcEditDeviceDto dmcEditDeviceDto, BindingResult br) {

        DmcDevice dmcDeviceOld = dmcDeviceService.selectByKey(dmcEditDeviceDto.getId());

        DmcDevice dmcDevice = new DmcDevice();
        BeanUtils.copyProperties(dmcEditDeviceDto, dmcDevice);
        dmcDevice.setDeviceType(DmcDeviceTypeEnum.CSUN_SLEEP.getIndex());

        Integer result = dmcDeviceService.editDevice(dmcDevice, getLoginAuthDto());
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        } else {
            // 判断是否修改床垫编号
            if (!dmcDeviceOld.getDeviceNo().equals(dmcEditDeviceDto.getDeviceNo())) {
                // 删除旧的redisKey, 添加新的redisKey
                String redisKey = RedisKeyUtil.getCsunSleepKey(dmcDeviceOld.getDeviceNo());
                CsunSleepData csunSleepData = (CsunSleepData) redisTemplate.opsForValue().get(redisKey);
                if (PublicUtil.isNotEmpty(csunSleepData)) {
                    csunSleepData.setDeviceNo(dmcEditDeviceDto.getDeviceNo());
                    csunSleepData.setGroupId(dmcDeviceOld.getGroupId());

                    redisTemplate.delete(redisKey);

                    String newRedisKey = RedisKeyUtil.getCsunSleepKey(dmcEditDeviceDto.getDeviceNo());
                    redisTemplate.opsForValue().set(newRedisKey, csunSleepData);
                }
            }
        }

       // return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /**
     * 根据Id删除日创床垫
     *
     * @param id    the id
     *
     * @return  the wrapper
     */
    @ApiOperation(httpMethod = "POST", value = "根据Id删除日创床垫")
    @RequestMapping(value = "/deleteById/{id}", method = RequestMethod.POST)
    public Wrapper deleteDmcCsunSleepById(@PathVariable Long id) {

        DmcDevice dmcDeviceOld = dmcDeviceService.selectByKey(id);

        Integer result = dmcCsunSleepBindService.deleteCsunSleepById(id);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        } else {
            redisTemplate.delete(RedisKeyUtil.getCsunSleepKey(dmcDeviceOld.getDeviceNo()));
            DmcDeviceOnlineRecord dmcDeviceOnlineRecord = new DmcDeviceOnlineRecord();
            dmcDeviceOnlineRecord.setDeviceId(id);
            int delete = dmcDeviceOnlineRecordService.delete(dmcDeviceOnlineRecord);
        }

       // return WrapMapper.ok();
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /**
     * 绑定日创床垫
     *
     * @param bindCsunSleepDto bind csun button dto
     *
     * @return the wrapper.
     */
    @ValidateAnnotation
    @RequestMapping(value = "/bindCsunSleep", method = RequestMethod.POST)
    public Wrapper bindCsunSleep(@Validated @RequestBody BindCsunSleepDto bindCsunSleepDto,
                                          BindingResult br) {

        // DmcDevice dmcDevice = dmcDeviceService.selectByKey(bindCsunSleepDto.getDeviceId());

        Integer result = dmcCsunSleepBindService.bindCsunSleep(bindCsunSleepDto, getLoginAuthDto());
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }

        //return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /**
     * 解绑日创床垫
     *
     * @param deviceId  device id
     *
     * @return  the wrapper.
     */
    //@LogAnnotation(isSaveResponseData = true, isSaveRequestData = true)
    @RequestMapping(value = "/breakCsunSleep/{deviceId}", method = RequestMethod.POST)
    public Wrapper breakCsunSleep(@PathVariable Long deviceId) {

        // DmcDevice dmcDevice = dmcDeviceService.selectByKey(deviceId);

        Integer result = dmcCsunSleepBindService.breakCsunSleep(deviceId);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }

        DmcDeviceOnlineRecord dmcDeviceOnlineRecord = new DmcDeviceOnlineRecord();
        dmcDeviceOnlineRecord.setDeviceId(deviceId);
        int delete = dmcDeviceOnlineRecordService.delete(dmcDeviceOnlineRecord);
        //return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /**
     * 设置床垫wifi
     * @param: [csunSleepWifiDto]
     * @return: com.csun.cmny.util.wrapper.Wrapper
     */
   // @LogAnnotation(isSaveResponseData = true, isSaveRequestData = true)
    @RequestMapping(value = "/setCsunSleepWifi", method = RequestMethod.POST)
    public Wrapper setCsunSleepWifi(@RequestBody CsunSleepWifiDto csunSleepWifiDto) {
        int ret = dmcCsunSleepWifiService.setCsunSleepWifi(csunSleepWifiDto,getLoginAuthDto());
       // return WrapMapper.ok(ret);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),ret);
    }

    /**
     * 获取床垫wifi设置
     * @param: [deviceId]
     * @return: com.csun.cmny.util.wrapper.Wrapper
     */
   // @LogAnnotation(isSaveResponseData = true, isSaveRequestData = true)
    @RequestMapping(value = "/getCsunSleepWifi/{deviceId}", method = RequestMethod.POST)
    public Wrapper getCsunSleepWifi(@PathVariable Long deviceId) {
        DmcCsunSleepWifi dmcCsunSleepWifi = dmcCsunSleepWifiService.selectByKey(deviceId);
      //  return WrapMapper.ok(dmcCsunSleepWifi);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),dmcCsunSleepWifi);
    }

    /**
     * App 使用 -- 直接从床垫绑定表中获取老人信息
     *
     * @return
     */
    @RequestMapping(value = "/queryOldmanByDeviceId/{deviceId}", method = RequestMethod.POST)
    public Wrapper queryOldmanByDeviceId(@PathVariable Long deviceId) {

        DmcCsunSleepBind dmcCsunSleepBind = dmcCsunSleepBindService.selectByKey(deviceId);
        if (dmcCsunSleepBind != null) {
            // 根据老人Id获取老人姓名
            OldmanBedRoomBuildingVo oldmanBedRoomBuildingVo = omcRpcService
                    .queryOldmanBedRoomBuildingByOldmanId(dmcCsunSleepBind.getOldmanId());
            if (PublicUtil.isNotEmpty(oldmanBedRoomBuildingVo)) {   // 如果查到，显示实时的姓名
                dmcCsunSleepBind.setOldmanName(oldmanBedRoomBuildingVo.getOldmanName());
            }
        }

        // 如果查询的值
       // return WrapMapper.ok(dmcCsunSleepBind);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),dmcCsunSleepBind);
    }

    /**
      * @param dmcCsunSleepBind
     * @return null
     * @author HD
     * @date 2021/12/10 16:06
     */
    @PostMapping("/setActionDuration")
    public Wrapper setActionDuration(@RequestBody DmcCsunSleepBind dmcCsunSleepBind){
        DmcCsunSleepBind csunSleepBind = new DmcCsunSleepBind();
        csunSleepBind.setActionDuration(dmcCsunSleepBind.getActionDuration());
        csunSleepBind.setDeviceId(dmcCsunSleepBind.getDeviceId());
        Integer result = dmcCsunSleepBindService.update(csunSleepBind);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /**
     * 守护佳床垫报警按时间分布
     * @return Wrapper
     */
    @PostMapping("/selectSleepAlertByhour")
    public Wrapper selectSleepAlertByhour(){
        Long groupId = getLoginAuthDto().getGroupId();
        SleepAlertByHour sleepAlertByHour = dmcDeviceAlertService.selectSleepAlertByhour(groupId);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),sleepAlertByHour);
    }

}
